package com.sanjishu.enterlab.electricity.sale.utils;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Component
public class HttpInvoke {

    private static final Logger log = LoggerFactory.getLogger(HttpInvoke.class);

    @Autowired
    private RestTemplate restTemplate;

    public <T> T postForObject(String url, Class<T> responseType, String data) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity requestEntity = new HttpEntity(data, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        log.info("url:{} data:{} response:{}", url, data, response);
        return JSON.parseObject(response.getBody(), responseType);
    }

    public ResponseEntity<String> postForObject(String url, String data) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity requestEntity = new HttpEntity(data, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        log.info("url:{} data:{} response:{}", url, data, response);
        return response;
    }

    public ResponseEntity<String> getForObject(String url, List<String> keys, List<Object> values) {
        ResponseEntity<String> response = null;
        if (keys != null && keys.size() > 0) {
            url += "?";
            for (int i =0;i<keys.size(); i++) {
                url += keys.get(i) + "={" + i + "}" + "&";
            }
            url = url.substring(0, url.length() - 1);
            response = restTemplate.exchange(url, HttpMethod.GET, null, String.class, values.toArray());
        } else {
            response = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        }
        log.info("url:{} data:{}", url, "");
        return response;
    }


}
